#!/usr/bin/env python
import sys
import cv2
import ctypes
import json
import numpy as np

# self.lib.read_.restype = ctypes.c_ulong

# def read(self):
#     value = self.lib.read_(0)
#     sz = np.frombuffer(ctypes.string_at(value, 4*2),
#                        dtype=np.uint32, count=2)
#     image = np.frombuffer(ctypes.string_at(
#         value+4*2, sz[0]*sz[1]*3), dtype=np.uint8, count=3*sz[0]*sz[1]).reshape(sz[0], sz[1], 3)
#     return image


class mainStru(ctypes.Structure):
    _fields_ = [
        ("len", ctypes.c_int),
        ("ptr", ctypes.c_void_p)
    ]


np.set_printoptions(precision=3, suppress=True)
names=["electric_scooter","person","bicycle","others"]

class getRGB():
    def __init__(self) -> None:
        ll = ctypes.cdll.LoadLibrary
        self.lib = ll("./libmain.so")
        self.obj = mainStru()
        self.lib.dump_.restype = ctypes.c_int

    def send(self, image):
        image_data = image.ctypes.data_as(ctypes.c_void_p)
        value = self.lib.dump_(ctypes.byref(self.obj),
                               image.shape[0], image.shape[1], image_data)
        # print("bl",g.obj.len)
        # val=np.frombuffer(ctypes.string_at(g.obj.ptr, g.obj.len),dtype=np.uint32, count=g.obj.len)
        # print(val)


def init():

    mode = getRGB()
    return mode

def process_image(handle=None, input_image=None, args=None, ** kwargs):

    handle.send(input_image)
    bsz = (ctypes.string_at(handle.obj.ptr, handle.obj.len*4*6))
    ba = np.frombuffer(bsz, dtype=np.int32,
                       count=handle.obj.len*6).reshape(-1, 6)
    target_info = []
    for cf, x, y, w, h,idx_ in ba:
        _obj = {
            "x": int(x),
            "y": int(y),
            "width": int(w),
            "height": int(h),
            "confidence": float(cf*0.001),
            "name": names[idx_]
        }
        target_info.append(_obj)
    fake_result = {}
    fake_result["algorithm_data"] = {
        "is_alert": len(target_info) > 0,
        "target_count": len(target_info),
        "target_info": target_info
    }
    fake_result["model_data"] = {"objects": target_info}
    return json.dumps(fake_result, indent=4)


if __name__ == '__main__':
    img = cv2.imread("../p2.jpg")
    g = init()
    for i in range(20):
        ans = process_image(g, img)
        # print(g.obj.len)
        print(ans.strip())
        break
